<template>
	<e-popup :show="modelValue" round="20rpx">
		<view class="wholesale-popup-body bg-white">
			<view class="e-flex">
				<view class="category-one" v-if="categoryOne">
					<scroll-view scroll-y="true" class="category-one-scroll">
						<view class="category-item e-flex e-flex-xy-center"
							:class="{'bg-white': selectIds.includes(item.id)}" v-for="item in categoryOne"
							:key="item.id" @tap="handleTapCategory(0, item.id)">
							<text>{{item.name}}</text>
						</view>
					</scroll-view>
				</view>
				<view class="e-rela e-flex-1">
					<image class="close-btn img-40" :src="$staticPath('classify/close.png')" @tap.stop="handleClose">
					</image>
					<view class="bg-white e-p-40 h-320 e-flex">
						<image class="img-238" :src="$fullLink(skuCoverImg)" mode="aspectFit"></image>
						<view class="e-p-l-40 e-p-r-30" v-if="wholesalePricingRules">
							<view class="e-m-b-20" v-for="(item, index) in wholesalePricingRules" :key="index">
								<view class="c-red e-font-24 fw-500">
									<text>{{$unitEn}}</text>
									<text class="e-font-32">{{item.pricing}}</text>
								</view>
								<view class="c-secondary e-font-20 text-center">
									<template v-if="item.maximum">
										<text>{{item.minimum}}</text>
										-
										<text>{{item.maximum}}</text>
									</template>
									<template v-else>
										<text>≥{{item.minimum}}</text>
									</template>
								</view>
							</view>
						</view>
					</view>
					<view class="category-other e-flex e-flex-items-start">
						<view class="" v-if="categoryTwo&&categoryTwo.length">
							<scroll-view scroll-y="true" class="category-other-one-scroll">
								<view class="category-other-item e-flex e-flex-xy-center"
									:class="{'bg-white': selectIds.includes(item.id)}" v-for="item in categoryTwo"
									:key="item.id" @tap="handleTapCategory(1, item.id)">
									<text>{{item.name}}</text>
								</view>
							</scroll-view>
						</view>
						<view v-else class="category-other-item"></view>
						<view class="" v-if="categoryThree&&categoryThree.length">
							<scroll-view scroll-y="true" class="category-other-two-scroll">
								<view class="category-other-item e-flex e-flex-xy-center"
									:class="{'bg-white': selectIds.includes(item.id)}" v-for="item in categoryThree"
									:key="item.id" @tap="handleTapCategory(2, item.id)">
									<text>{{item.name}}</text>
								</view>
							</scroll-view>
						</view>
						<view v-else class="category-other-item"></view>
						<view class="e-flex e-p-30 e-flex-1 bg-white">
							<image class="img-32" :src="$staticPath('classify/sub.png')" @tap="sub"></image>
							<view class="e-m-12 num-box e-flex-1 e-p-10 e-flex e-flex-xy-center">
								<input class="text-center" v-model="number" type="number" name="" id="">
							</view>
							<image class="img-32" :src="$staticPath('classify/add.png')" @tap="add"></image>
						</view>
					</view>
				</view>
			</view>
			<view class="wholesale-select-box e-p-l-30 e-p-r-30 bg-white e-flex e-flex-between">
				<view class="e-font-24 c-80">
					{{$t('classify.selected')}}
					<text class="e-p-4">{{result.num}}</text>
					{{$t('classify.species')}}
					<text class="e-p-4">{{result.piece}}</text>
					{{$t('classify.件')}}
				</view>
				<view class="e-font-24 c-333">
					{{$t('classify.goodsAmount')}}:
					<text class="c-red e-font-24 e-p-l-6">{{$unitEn}}{{result.money}}</text>
				</view>
			</view>
			<view class="e-p-l-30 e-p-r-30 bg-white">
				<e-button size="large" type="primary" shape="circle" :text="$t(btnText)" @click="confirm"
					:throttleTime="1000"></e-button>
			</view>
		</view>
	</e-popup>
</template>

<script lang="ts" setup>
	import { ref, reactive, computed, watch } from 'vue'
	import type { GoodsSkuInfo } from '../type'
	import {
		useCurrentInstance
	} from '@/common/hooks'
	import { arrayDeepClone } from '@/common/utils'


	type ProductSkuSpecifications = GoodsSkuInfo['productSkuSpecifications']
	type ProductSkuSpecificationsItem = ProductSkuSpecifications[0]
	type Category = ProductSkuSpecificationsItem['productSkuValues']

	type _GoodsSkuInfo = Omit<GoodsSkuInfo, 'productSkuSpecifications'> & {
		productSkuSpecifications : Array<ProductSkuSpecificationsItem & { number : number }>
	}

	const props = defineProps<{
		modelValue : boolean,
		popupType : 1 | 2,
		primary : string,
		info : _GoodsSkuInfo,
	}>()

	const emit = defineEmits(['update:modelValue', 'buy', 'addCart'])

	const ctx = useCurrentInstance()





	let productSkuSpecifications : _GoodsSkuInfo['productSkuSpecifications'] = []

	const categoryOne = ref<Category>([])
	const categoryTwo = ref<Category>([])
	const categoryThree = ref<Category>([])
	const selectIds = ref<number[]>([])

	watch(props.info, (val) => {
		if (val && val.productSkuSpecifications) {
			productSkuSpecifications = val.productSkuSpecifications
			productSkuSpecifications?.forEach(item => item.number = 0)
			categoryOne.value = val.productSkus[0]?.productSkuValues
			categoryTwo.value = val.productSkus[1]?.productSkuValues
			categoryThree.value = val.productSkus[2]?.productSkuValues
			selectIds.value = [categoryOne.value[0].id]
			if (categoryTwo.value) selectIds.value.push(categoryTwo.value[0].id)
			if (categoryThree.value) selectIds.value.push(categoryThree.value[0].id)
			getSkuCoverImg()
			getWholesalePrice()
		}

	}, {
		deep: true,
		immediate: true
	})


	const number = ref(0)

	watch(number, (val) => {

		const index = getIndex()
		const stock = productSkuSpecifications[index].stock
		if (stock >= +val) {
			productSkuSpecifications[index].number = +val
		} else {
			number.value = stock
			ctx.$toastApp(ctx.$t('classify.商品库存不足'))
		}
		calcResultPiece()
		calcResultMoney()

	})

	const btnText = computed(() => {
		return props.popupType === 1 ? 'classify.立即购买' : 'common.确定'
	})


	const handleClose = () => {
		emit('update:modelValue', false)
	}
	const result = reactive<{
		num : number
		piece : string | number
		money : string | number
	}>({
		num: 0,
		piece: 0,
		money: 0
	})
	const confirm = () => {
		if (!result.piece) {
			ctx.$toastApp(ctx.$t('classify.qxzsp'))
			return
		}
		// 判断是否有设置批发价
		if (productSkuSpecifications.some(item => !item.wholesalePricingRules)) {
			ctx.$toastApp(ctx.$t('classify.gsppfsjyc'))
			return
		}
		// 判断购买数量是否在批发范围内
		const __whole = arrayDeepClone(productSkuSpecifications[0].wholesalePricingRules || [])
		const list = __whole.sort((a, b) => a.minimum - b.minimum)
		if (list[0].minimum > result.piece) {
			ctx.$toastApp(ctx.$t('classify.bdbz'))
			return
		}

		emit(props.popupType === 1 ? 'buy' : 'addCart', 1, productSkuSpecifications)
	}
	const add = () => {
		const index = getIndex()
		const stock = productSkuSpecifications[index].stock
		if (stock >= +number.value) {
			number.value++
		} else {
			ctx.$toastApp(ctx.$t('classify.商品库存不足'))
		}
	}
	const sub = () => {
		if (number.value > 0) {
			number.value--
		}
	}
	const handleTapCategory = (index : number, id : number) => {
		selectIds.value.splice(index, 1, id)
		getSkuCoverImg()
		getWholesalePrice()
		const idx = getIndex()
		if (productSkuSpecifications[idx].number) {
			number.value = productSkuSpecifications[idx].number
		} else {
			number.value = 0
		}

	}
	// 计算已选多少件
	const calcResultPiece = () => {
		let num = 0; // 种
		let piece = 0; // 件
		productSkuSpecifications.forEach(item => {
			if (item.number) {
				num++
				piece = piece + item.number
			}
		})
		result.num = num
		result.piece = piece
	}
	// 计算已选商品金额
	const calcResultMoney = () => {
		let money : string | number = 0; // 金额
		// 达到起批量用批发价，否则用原价(起批量是当前商品所有规格的购买数量即result.piece)
		const __whole = arrayDeepClone(productSkuSpecifications[0].wholesalePricingRules || [])
		const minList = __whole.sort((a, b) => a.minimum - b.minimum)
		if (minList[0].minimum > result.piece) {
			productSkuSpecifications.forEach(item => {
				if (item.number) {
					money = (+money + item.number * item.price).toFixed(2)
				}
			})
		} else {
			productSkuSpecifications.forEach(item => {
				if (item.number) {
					// 如果达到起批量则用对应的批发价，否则用最低起批量所对应的批发价
					const flag = item.wholesalePricingRules?.some(list => {
						if (list.maximum) {
							if (result.piece >= list.minimum && result.piece <= list.maximum) {
								money = (+money + item.number * list.pricing).toFixed(2)
								return true
							}
						} else {
							if (result.piece >= list.minimum) {
								money = (+money + item.number * list.pricing).toFixed(2)
								return true
							}
						}
					})
					if (!flag) {
						// 如果不在批发范围内，按原价计算
						money = (+money + item.number * item.price).toFixed(2)
					}
				}
			})
		}
		result.money = Number(money)

	}
	const getIndex = () => {
		if (selectIds.value.length > 1) {
			return productSkuSpecifications.findIndex(idx => idx.skuKey === selectIds.value.join('/'))
		} else {
			return productSkuSpecifications.findIndex(idx => idx.skuKey === selectIds.value.join(''))
		}
	}
	const skuCoverImg = ref('')
	const getSkuCoverImg = () => {
		const index = getIndex()
		skuCoverImg.value = productSkuSpecifications[index].skuCoverImg
	}
	const wholesalePricingRules = ref<ProductSkuSpecifications[0]['wholesalePricingRules']>([])
	const getWholesalePrice = () => {
		const index = getIndex()
		wholesalePricingRules.value = productSkuSpecifications[index].wholesalePricingRules
	}
</script>

<style lang="scss" scoped>
	.wholesale-popup-body {
		height: 90vh;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;
	}

	.wholesale-select-box {
		height: 80rpx;
	}

	.c-80 {
		color: #808080;
	}

	.category-one {
		width: 200rpx;
		overflow-y: auto;
	}

	.category-item {
		height: 120rpx;
		color: #424242;
		font-size: 24rpx;
	}

	.category-one-scroll {
		height: calc(90vh - 80rpx - 100rpx);
		background-color: #F7F7F7;
	}

	.close-btn {
		position: absolute;
		top: 40rpx;
		right: 30rpx;
	}

	.h-320 {
		height: 320rpx;
		width: 100%;
	}

	.category-other {
		height: calc(90vh - 180rpx - 320rpx);
		width: 100%;
	}

	.category-other-one-scroll,
	.category-other-two-scroll {
		height: calc(90vh - 180rpx - 320rpx);
		background-color: #F7F7F7;
	}

	.category-other-item {
		height: 120rpx;
		width: 160rpx;
		color: #424242;
		font-size: 24rpx;
	}

	.num-box {
		height: 44rpx;
		background: #F2F2F2;
		border-radius: 4rpx;
	}

	.img-238 {
		width: 238rpx;
		height: 238rpx;
	}
</style>